package lesson.teacher;

import lesson.base.BaseServlet;
import lesson.permission.Role;
import lesson.user.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.List;

@WebServlet("/teacher/*")
@Role(User.ROLE_ADMIN)
public class TeacherServlet extends BaseServlet {

    private TeacherService teacherService = new TeacherService();

    /**
     * 教师管理的首页
     */
    public void index() {
        forwardJsp("/pages/teacher/index");
    }

    /**
     * 教师管理的编辑页面
     */
    public void edit(Integer id) {
        if (id != null) {
            Teacher teacher = teacherService.getById(id);
            getRequest().setAttribute("teacher", teacher);
        }
        forwardJsp("/pages/teacher/edit");
    }


    /**
     * 查询教师
     */
    public void list(String keywords) throws ServletException, IOException {
        List<Teacher> list = teacherService.list(keywords);
        writeJSON(true, null, list);
    }


    /**
     * 删除教师
     * @param id
     */
    public void del(Integer id) throws ServletException, IOException {
        String result = teacherService.del(id);
        if (result == null) {
            writeJSON(true);
        } else {
            writeJSON(false, result);
        }
    }


    /**
     * 保存教师
     * @throws ServletException
     * @throws IOException
     */
    public void save(Teacher teacher) throws ServletException, IOException {

        String result = teacherService.saveTeacher(teacher);
        if (result == null) {
            writeJSON(true);
        } else {
            writeJSON(false, result);
        }
    }

    public void assign(Integer id) {
        getRequest().setAttribute("teacherId", id);
        forwardJsp("/pages/teacher/assign");
    }

}
